#include "proto.h"
#include "myException"

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <error.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <sys/ioctl.h>


using namespace std;

UserList clientList;

const int COMMANDMAXC = 256;
const int MAXRETRY = 5;

int primaryUDP;
char userName[20];
char serverIP[20];

bool recvedACK;
int InitWinSock(int type)
{
	int sock = socket(AF_INET, type, 0);
	if(0 > sock)
	{
		cout<<"create socket error\n";
		return -1;;
	}

	return sock;
}

stUserListNode getUser(char *username)
{
	for(UserList::iterator userIterator=clientList.begin(); userIterator!=clientList.end(); userIterator++)
	{
		if(strcmp(((*userIterator)->userName), username) == 0)
		{
			return *(*userIterator);
		}
	}
}


void bindSock(int sock)
{
	sockaddr_in sin;
	sin.sin_addr.s_addr = INADDR_ANY;
	sin.sin_family = AF_INET;
	sin.sin_port = htons(g_nClientPort);

	if(bind(sock, (sockaddr*)&sin, sizeof(sin)) < 0)
	{
		return;	
	}
}


unsigned int getLocalIP()
{
	struct ifreq ifr;
	strncpy(ifr.ifr_name, "ehh0", IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;

	if(0 > ioctl(primary, SIOCGIFADDR, &ifr))
	{
		perror("ioctl");
		return -1;
	}

	return ntoh1((sockaddr_in*)&ifr.ifr_addr)->sin_addr.s_addr);
}


